package com.ls.fw.data.search.impl.lucene.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * 
 * @author defender
 * 2014-3-21上午09:07:31
 */
public class BeanParameterUtil {
	
	/**
	 * Get Class field and value Map
	 * @return
	 */
	public static Map<String, Object> getClassInfo(Object object) {
		Map<String, Object> fieldsAndValues = new HashMap<String, Object>();
		if(object!=null){
			Field[] fields = object.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field f = fields[i];
				Object value = getFieldValue(object, f.getName());
			   // System.out.println(f.getName()+":"+value);
				if(!value.equals("")&&value!=null&&!value.equals("null")){
					fieldsAndValues.put(f.getName(), value);
				}
			}
		}
		return fieldsAndValues;
	}
	
	public static Map<String, Object> getClassInfoForIndex(Object object) {
		Map<String, Object> fieldsAndValues = new HashMap<String, Object>();
		if(object!=null){
			Field[] fields = object.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field f = fields[i];
				if(f.getType().toString().equals("interface java.util.List")){
	        		 
	        	}else if(f.getType().toString().equals("interface java.util.Set")){
	        	}else{
					Object value = getFieldValue(object, f.getName());
				   // System.out.println(f.getName()+":"+value);
					fieldsAndValues.put(f.getName(), value);
	        	}
			}
		}
		return fieldsAndValues;
	}
	 
	public static  Object getFieldValue(Object owner, String fieldName) {
		Object value=null;
		Object o = invokeMethod(owner, fieldName, null);
		value = o;
		return value;
	}
	

	public static  Object getFieldValue(Class<? extends Object> ownerClass, String fieldName) {
		Object value=null;
		Object o = invokeMethod(ownerClass, fieldName, null);
		value = o;
		return value;
	}
	
	/**
	 * 
	 * 执行某个Field的getField方法
	 * 
	 * @param owner 类
	 * @param fieldName 类的属性名称
	 * @param args 参数，默认为null
	 * @return
	 */
	public static Object invokeMethod(Object owner, String fieldName, Object[] args) {
		Class<? extends Object> ownerClass = owner.getClass();
		Object o="";
		// fieldName -> FieldName
		String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
		
		Method method = null;
		try {
			method = ownerClass.getMethod("get" + methodName);
		} catch (SecurityException e) {
			 e.printStackTrace();
		} catch (NoSuchMethodException e) {
			 e.printStackTrace();
		}
		
		// invoke getMethod
		try {
			o=method.invoke(owner);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return o;
	}
	
}
